package nina.yiyou.paystub.input

import javax.imageio.ImageIO
import java.awt.Image
import java.awt.Toolkit
import java.awt.datatransfer.Clipboard
import java.awt.datatransfer.DataFlavor
import java.awt.datatransfer.Transferable
import java.awt.image.BufferedImage
import java.nio.file.Files
import java.nio.file.Path

class ClipboardImageReader {

  ClipboardImageReader(Path resultExcel) {
    _resultExcel = resultExcel
  }

  Image read() {
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard()
    Transferable content = clipboard.getContents(null)

    if (content == null) {
      Path imgPath = getImagePath()
      if (Files.isRegularFile(imgPath)) {
        return readImageCache(imgPath)
      }
    }

    assert content && content.isDataFlavorSupported(DataFlavor.imageFlavor)

    def image = (BufferedImage) content.getTransferData(DataFlavor.imageFlavor)
    ImageIO.write(image, 'png', imagePath.toFile())

    return image
  }

  private Path getImagePath() {
    String oldName = _resultExcel.fileName.toString()
    String newName = oldName.take(oldName.lastIndexOf('.')) + '.png'
    return _resultExcel.resolveSibling(newName)
  }

  private Image readImageCache(Path path) {
    return ImageIO.read(path.toFile())
  }

  private final Path _resultExcel
}
